﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Web.Security;

namespace JobSeek.Classes
{
    public class ParentMembershipProvider
    {
        protected bool SendEmail(string body, string subject, string email)
        {

            MailMessage mailMessage = new MailMessage();
            mailMessage.To.Add(email);
            mailMessage.From = new MailAddress("");
            mailMessage.Body = body;
            mailMessage.IsBodyHtml = true;
            mailMessage.Subject = subject;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com");
            smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = true;
            smtp.Credentials = new System.Net.NetworkCredential("", "");
            smtp.Port = 587;
            try
            {
                smtp.Send(mailMessage);
                return true;
            }
            catch (Exception ex)
            {
                //Log error here!
                return false;
            }
        }

        protected static string CreateSalt(int size)
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] bytes = new byte[size];

            rng.GetBytes(bytes);

            return Convert.ToBase64String(bytes);
        }
        /// <summary>
        /// Generate a hash password for the new password. Password will be hashed with a auto generate salt.
        /// </summary>
        /// <param name="password">new password</param>
        /// <param name="User"></param>
        /// <param name="ctx"></param>
        /// <returns>return a hashed password</returns>
        protected static string CreateHashPassword(string password, string salt)
        {

            string saltAndPwd = salt + password;

            string hashPwdAndSalt = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "SHA1");

            return hashPwdAndSalt;


        } 
        
        /// <summary>
        /// Generate a random password
        /// </summary>
        /// <returns>returns random password</returns>
        protected string GenerateRandPassword()
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

            Random rand = new Random();

            string randPassword = new string(Enumerable.Repeat(chars, 8).Select(s => s[rand.Next(s.Length)]).ToArray());

            return randPassword;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="username">Can be username of Advertiser OR email or Applicant.</param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        protected bool ChangePassword(string username, string oldPassword, string newPassword, string role)
        {
            bool success = false;
            string email = "";
            string salt = CreateSalt(new Random().Next(1, 100));
            switch (role)
            {
                case "Advertiser":
                    using (job_seekerEntities ctx = new job_seekerEntities())
                    {

                        Advertiser advertiser = (from emp in ctx.Advertisers
                                                 where emp.username == username
                                                 where emp.password == oldPassword
                                                 select emp).SingleOrDefault<Advertiser>();
                        if (advertiser != null)
                        {

                            string hashPwdAndSalt = CreateHashPassword(newPassword, salt);

                            advertiser.password = hashPwdAndSalt;

                            try
                            {
                                ctx.SaveChanges();
                                email = advertiser.email;
                                success = true;
                            }
                            catch (Exception ex)
                            {
                                //log error here;
                                success = false;
                            }
                        }
                    }
                    break;

                case "Applicant":
                    using (job_seekerEntities ctx = new job_seekerEntities())
                    {

                        Applicant applicant = (from emp in ctx.Applicants
                                               where emp.email == username
                                               where emp.password == oldPassword
                                               select emp).SingleOrDefault<Applicant>();

                        string hashPwdAndSalt = CreateHashPassword(newPassword, salt);

                        if (applicant != null)
                        {
                            applicant.password = hashPwdAndSalt;

                            try
                            {
                                ctx.SaveChanges();
                                email = applicant.email;
                                success = true;
                            }
                            catch (Exception ex)
                            {
                                //Log error here!
                                success = false;
                            }
                        }
                    }

                    break;
                case "Administrator":
                    break;
                default:
                    success = false;
                    break;
            }

            if (success)
            {
                string body = "Your password has been change.";
                string subject = "Password changed";

                SendEmail(body, subject, email);
            }
            return success;
        }
    }
}